package com.hmall.search.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImlp implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    ItemClient itemClient;




    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) throws IOException {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.不要文档数据
            request.source().size(0);
            // 2.2.query条件
            buildBasicQuery(request, requestParams);

            // 2.3.聚合条件
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(20)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(20)
            );
            // 3.发请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> map = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据名称获取品牌聚合
            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                brandList.add(key);
            }
            map.put("brand", brandList);
            // 4.2.根据名称获取分类聚合
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                categoryList.add(key);
            }
            map.put("category", categoryList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void save(Long id) throws IOException {
        Item item = itemClient.queryItemById(id);
        IndexRequest request = new IndexRequest("item").id(id.toString());
        String json = JSON.toJSONString(item);
        request.source(json, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

    @Override
    public void delete(Long id) throws IOException {
        DeleteRequest request = new DeleteRequest("item",id.toString());
        client.delete(request,RequestOptions.DEFAULT);
    }


    private void buildBasicQuery(SearchRequest request, RequestParams params) {
        // 1.创建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1. key
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            // 非空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            // 空
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 1.2. brand
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3. category
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        // 1.4. price
        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }

        // 2.放入request
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );
        request.source().query(queryBuilder);
    }
}
